<template>
	<div class="w-full">
		<n-input-group>
			<n-select :style="{ width: '25%' }"
			          v-model:value="iconLibrary"
			          :options="iconLibrarys"
			          @update:value="updateIconLibrary"
			          placeholder="选择图标库" />
			<n-select
				v-model:value="iconValue"
				filterable
				placeholder="选择图标"
				:options="icons"
				@update:value="updateIcon"
				:render-label="renderLabel"
			/>
		</n-input-group>
	</div>
</template>

<script lang="ts" setup>
import {carbonIcon, getCarbonIcons, getIonicons5Icons, ionicons5Icon} from "@/utils/icon"
import {h, ref, watch} from "vue"
import {NIcon, NSpace} from "naive-ui"

const emit = defineEmits(["update:value", "update:library"])
const props = defineProps({
	value: {
		type: String,
		default: "",
	},
	library: {
		type: String,
		default: "",
	},
})

const iconValue = ref(props.value)

// 图标库
const iconLibrarys = [
	{
		label: "carbon",
		value: "carbon",
	},
	{
		label: "ionicons5",
		value: "ionicons5",
	},
]

const iconLibrary = ref("carbon")
emit("update:library", iconLibrary.value)

watch(() => props.value, (value) => {
	iconValue.value = value
})
watch(() => props.library, (value) => {
	updateIconLibrary(value || "carbon")
})

const updateIcon = (value: string) => {
	emit("update:value", value)
}

const getIcons = (type: string) => {
	let icons
	switch (type) {
		case "carbon":
			icons = getCarbonIcons()
			break
		case "ionicons5":
			icons = getIonicons5Icons()
			break
	}
	
	let keys = Object.keys(icons)
	
	return keys.map(key => {
		return {
			label: key,
			value: key,
		}
	})
}

const icons = ref(getIcons(iconLibrary.value))

const updateIconLibrary = (value: string) => {
	iconLibrary.value = value
	icons.value = getIcons(value)
	iconValue.value = ""
	
	emit("update:library", value)
}

const getIcon = (name: string) => {
	switch (iconLibrary.value) {
		case "carbon":
			return carbonIcon(name)
		case "ionicons5":
			return ionicons5Icon(name)
	}
}

const renderLabel = (option: { label: "", value: "" }) => {
	return h(
		NSpace,
		{
			class: "flex items-center",
		},
		{
			default: () => [
				h(
					NIcon,
					{
						component: getIcon(option.value),
						size: 18,
						class: "flex items-center",
					},
				),
				option.label as string,
			],
		},
	)
}
</script>
